<!--健康档案队列-->
<template>
  <div class="p-2">
    <el-row>
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <div class="head_tag_list">
            <div v-for="(tag, index) in tags" :key="index" class="tag_item"
                 :class="{ 'is-checked': selectedIndex == index }" @click="selectTag(index)">
              <span class="el-check-tag">{{ tag.label }}</span>
            </div>
          </div>
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="统计模式" prop="viewType">
              <el-select v-model="queryParams.viewType" placeholder="请选择统计模式" clearable>
                <el-option label="累计" value="0" />
                <el-option label="新增" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="年份" style="width: 308px">
              <el-date-picker
                v-model="queryParams.year"
                value-format="YYYY"
                type="year"
              />
            </el-form-item>
            <el-form-item label="季度" prop="quarter">
              <el-select v-model="queryParams.quarter" placeholder="请选择季度" clearable>
                <el-option label="第一季度" value="1" />
                <el-option label="第二季度" value="2" />
                <el-option label="第三季度" value="3" />
                <el-option label="第四季度" value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="档案机构：" prop="orgCode">
              <el-tree-select
                v-model="queryParams.orgCode"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择归属机构"
                check-strictly
                @change="getTreeSelect"
                clearable
              />
            </el-form-item>
            <el-form-item label="居民姓名：" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="责任医生：" prop="doctorCode">
              <el-select v-model="queryParams.doctorCode" placeholder="请选择责任医生" clearable
                         @keyup.enter="handleQuery">
                <el-option v-for="item in doctorDictLists" :key="item.deptId" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="身份证号：" prop="idCard">
              <el-input v-model="queryParams.idCard" placeholder="请输入身份证号" clearable
                        @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label-width="120px">
              <el-button type="primary" icon="Search" @click="handleQuery('search')">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
            <el-col :span="24">
              <el-form-item label=" 人群标签：" prop="sign">
                <el-checkbox-group v-model="queryParams.sign">
                  <el-checkbox label="2">高血压</el-checkbox>
                  <el-checkbox label="3">糖尿病</el-checkbox>
                  <el-checkbox label="1">老年人</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-form>
        </el-card>
      </div>
      <el-card shadow="hover">
        <el-table v-loading="loading" :data="patientInfoList" @selection-change="handleSelectionChange">
          <el-table-column label="姓名" align="center" prop="name" />
          <el-table-column label="身份证号" align="center" prop="idCard" width="200" />
          <el-table-column label="人群类型" align="center" prop="queueInfo" width="300">
            <template #default="scope">
              <dict-tag :options="bp_pt_sign" :value="scope.row.queueInfo" />
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="gender">
            <template #default="scope">
              <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
            </template>
          </el-table-column>
          <el-table-column label="年龄" align="center" prop="age" width="100" />
          <el-table-column label="个人电话" align="center" prop="personalPhone" width="200" />

          <el-table-column label="现管机构" align="center" prop="documentationUnitName" width="250" />
          <el-table-column label="体检" align="center" width="200">
            <template #default="scope">
              <span style="color: #31afee; text-decoration: underline; cursor: pointer;"
                    @click="Physical(scope.row)">去体检>>
              </span>
            </template>
          </el-table-column>

          <el-table-column label="随访" align="center" prop="follow" width="320">
            <template #default="scope">
              <el-tag type="success">高血压随访</el-tag>
              <el-tag type="info">糖尿病随访</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template #default="scope">
              <el-tooltip content="查看" placement="top">
                <el-button link type="primary" icon="View" @click="handleLook(scope.row)"
                           v-hasPermi="['basicPublic:patientInfo:edit']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getList('search')" />
      </el-card>
      <!-- </el-col>-->
    </el-row>

  </div>
</template>


<script setup name="PatientInfo" lang="ts">
import {
  listPatientInfo,
  getPatientInfo,
  delPatientInfo,
  addPatientInfo,
  updatePatientInfo
} from '@/api/basicPublic/patientInfo';
import {
  HealthRecordVO,
  HealthRecordQuery,
  HealthRecordForm
} from '@/api/basicPublic/patientInfo/healthRecord/HealthRecordTypes';
import { getLabelsByValues, parseTime, AddressConcatenation, getCurrentYearsArray } from '../../../utils/ruoyi';
import options from '@/assets/json/address.json';
import { useRouter } from 'vue-router';
import { globalHeaders } from '@/utils/request';
import { DeptVO } from '@/api/system/dept/types';
import api, { listUser } from '@/api/system/user';
import { UserQuery } from '@/api/system/user/types';
import { physicalExamination, getDiabetes, getHypertension } from '@/api/demo/tree/index';
import useUserStore from '@/store/modules/user';
// import Cascader from "@/components/Cascader/index.vue";

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  bp_pt_sign,
  sys_user_sex,
  bp_complete_status,
  bp_marital_status,
  bp_inspection_type,
  bp_contacts_relationship,
  bp_sign_status,
  bp_inspection_situation
} = toRefs<any>(proxy?.useDict('bp_inspection_situation', 'bp_sign_status', 'bp_contacts_relationship', 'bp_pt_sign', 'sys_user_sex', 'bp_complete_status', 'bp_marital_status', 'bp_inspection_type'));

const patientInfoList = ref<HealthRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);

const total = ref(0);
const deptName = ref('');
const deptOptions = ref<DeptVO[]>([]);
const uploadRef = ref<ElUploadInstance>();
const queryFormRef = ref<ElFormInstance>();
const patientInfoFormRef = ref<ElFormInstance>();
const documentationDateRange = ref([]);
const lastFollowupDateRange = ref([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: HealthRecordForm = {
  id: undefined,
  name: undefined,
  idCard: undefined,
  gender: undefined,
  birthday: undefined,
  maritalStatus: undefined,
  personalPhone: undefined,
  residentialAddress: undefined,
  registeredResidence: {
    province: undefined,//户籍地址-省
    provinceCode: undefined,//户籍地址-省代码
    city: undefined,//户籍地址-市
    cityCode: undefined,//户籍地址-市代码
    area: undefined,//户籍地址-区
    areaCode: undefined,//户籍地址-区代码
    street: undefined,//户籍地址-街道
    streetCode: undefined,//户籍地址-街道代码
    committee: undefined,//户籍地址-社区
    committeeCode: undefined,//户籍地址-社区代码
    detail: undefined//户籍地址-详细地址
  },
  currentResidentialAddress: {
    province: undefined,//户籍地址-省
    provinceCode: undefined,//户籍地址-省代码
    city: undefined,//户籍地址-市
    cityCode: undefined,//户籍地址-市代码
    area: undefined,//户籍地址-区
    areaCode: undefined,//户籍地址-区代码
    street: undefined,//户籍地址-街道
    streetCode: undefined,//户籍地址-街道代码
    committee: undefined,//户籍地址-社区
    committeeCode: undefined,//户籍地址-社区代码
    detail: undefined//户籍地址-详细地址
  },
  isMaternal: undefined,
  isChildren: undefined,
  contact: undefined,
  contactPhone: undefined,
  documentationTime: undefined,
  documentationPeople: undefined,
  dutyDoctor: undefined,
  archiveNumber: undefined,
  documentationUnit: undefined,
  documentationUnitName: undefined,
  contactPersonInfoRelation: undefined,
  contactPersonInfoName: undefined,
  contactPersonInfoPhone: undefined,
  contactPersonInfo: [
    {
      relation: undefined,
      name: undefined,
      phone: undefined
    }
  ]
};
const data = reactive<PageData<HealthRecordForm, HealthRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    year: parseTime(new Date(), '{y}'),
    quarter: '1',
    viewType: '0',
    deptId: useUserStore().deptId,
    sign: [],
    doctorCode: undefined,
    name: undefined,
    idCard: undefined,
    personalPhone: undefined,
    birthday: undefined,
    followupStatus: undefined,
    dutyDoctor: undefined,
    documentationUnit: undefined,
    documentationUnitName: undefined,
    lastInspectionDate: undefined,
    inspectionType: undefined,
    maritalStatus: undefined,
    gender: undefined,
    archiveNumber: undefined,
    documentationStartDate: undefined,
    documentationEndDate: undefined,
    nextFollowupDate: undefined,
    inspectionSituation: undefined,
    documentationPeople: undefined,
    isInspection: undefined,
    params: {},
    orgCode: useUserStore().deptId
  },
  rules: {}
});

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/basicPublic/patientInfo/importData'
});


const { queryParams, form, rules } = toRefs(data);
const tags = [
  { label: '待体检' },
  { label: '高血压待随访' },
  { label: '糖尿病待随访' }
];
const selectedIndex = ref(0); // 默认选中的索引

const handleSelectedAdress = (value) => {
  form.value.currentResidentialAddress = value;
};

const handleSelectedResidence = (value) => {
  form.value.registeredResidence = value;
};

const selectTag = async (index: any) => {
  selectedIndex.value = index; // 更新 selectedIndex
};
/** 获取医生字典 */
const doctorDictList = ref<any[]>([]);
const doctorDictLists = ref<any[]>([]);

const getDoctorDictList = async () => {
  const query: UserQuery = {
    pageNum: 1,
    pageSize: 10
    // 可选参数可以根据需要添加
  };
  const res = await listUser(query);
  doctorDictList.value = res.rows || [];
  doctorDictLists.value = doctorDictList.value.map(it => ({
    elTagClass: '',
    elTagType: '',
    label: it.nickName,
    value: String(it.userId)
  }));
};

/** 查询患者基本信息列表 */
const getList = async (type: string) => {
  loading.value = true;
  // if (!queryParams.value.orgCode && type == 'search') {
  //   proxy?.$modal.msgWarning("请选择档案机构");
  //   loading.value = false;
  //   return;
  // }
  if (selectedIndex.value == 0) { //待体检
    const res = await physicalExamination(queryParams.value);
    patientInfoList.value = res.rows as HealthRecordVO[];
    total.value = res.total;
    loading.value = false;
  } else if (selectedIndex.value == 1) {//高血压
    const res = await getHypertension(queryParams.value);
    patientInfoList.value = res.rows as HealthRecordVO[];
    total.value = res.total;
    loading.value = false;
  } else {//糖尿病
    const res = await getDiabetes(queryParams.value);
    patientInfoList.value = res.rows as HealthRecordVO[];
    total.value = res.total;
    loading.value = false;
  }
};
const setDateRange = (dateRange, startDateKey, endDateKey, pin) => {
  if (dateRange) {
    queryParams.value[pin][startDateKey] = parseTime(dateRange[0]);
    queryParams.value[pin][endDateKey] = parseTime(dateRange[1]);
  } else {
    queryParams.value[pin][startDateKey] = undefined;
    queryParams.value[pin][endDateKey] = undefined;
  }
};

/** 去体检操作 */
const Physical = (row?: HealthRecordVO) => {
  const path = '/index?';
  const token = localStorage.getItem('Admin-Token');
  const queryParams = new URLSearchParams({
    // redirect: '/workBenches/workBenches',
    id: String(row?.id),
    name: 'PhysicalExamination',
    token: token
  });

  // navigateWithToken(path);
  window.open(`http://127.0.0.1:88${path}${queryParams}`);
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  queryParams.value.idCard = undefined;
};


/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};


/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.orgCode = data.id;
  handleQuery('search');
};


/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};


const doctorDictListForm = ref<any[]>([]);

const handleDeptChange = async (value: number | string) => {
  const can = {
    deptId: value,
    pageNum: 1,
    pageSize: 10
  };
  const res = await listUser(can);
  doctorDictListForm.value = res.rows;
};


/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  patientInfoFormRef.value?.resetFields();
};


/** 搜索按钮操作 */
const handleQuery = (type: any) => {
  queryParams.value.pageNum = 1;
  getList(type);
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  lastFollowupDateRange.value = undefined;
  documentationDateRange.value = undefined;
  handleQuery('reset');
};

/** 重置按钮操作 */
const resetQuerys = () => {
  reset();
  queryParams.value.idCard = undefined;
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: HealthRecordVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加健康档案基本信息';
};


/** 查看按钮操作 */

const handleLook = (row?: HealthRecordVO) => {
  // console.log($router)
  router.push({
    path: '/workBenches/workBenches',
    query: {
      id: row?.id
    }
  });
};


/** 提交按钮 */
const submitForm = () => {
  patientInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.contactPersonInfo = [
        {
          relation: undefined,
          name: undefined,
          phone: undefined
        }
      ];
      form.value.contactPersonInfo[0].relation = form.value.contactPersonInfoRelation;
      form.value.contactPersonInfo[0].name = form.value.contactPersonInfoName;
      form.value.contactPersonInfo[0].phone = form.value.contactPersonInfoPhone;
      await addPatientInfo(form.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
    }
  });
};


/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('basicPublic/patientInfo/export', {
    ...queryParams.value
  }, `patientInfo_${new Date().getTime()}.xlsx`);
};

/** 打开导入表弹窗 */
/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '患者信息导入';
  upload.open = true;
};
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  // getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}


const handleChange = (value) => {
  console.log(getLabelsByValues(value, options));
};


onMounted(() => {
  getTreeSelect();
  getDoctorDictList();
  // getList('search');
});

</script>
<style scoped lang="scss">
::v-deep .el-cascader {
  .el-input {
    //width: 300px;
  }
}

.head_tag_list {
  padding-left: 20px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.tag_item {
  margin-right: 10px;
  font-weight: 400;
}

.el-check-tag {
  height: 40px;
  text-align: center;
  line-height: 40px;
  font-weight: 400;
  background-color: #eee;
  color: #555;
  display: inline-block;
  /* 确保标签有合适的宽度 */
  padding: 0 20px;
  /* 根据需要调整内边距 */
  border-radius: 4px;
  /* 可选：添加圆角 */
}

.is-checked .el-check-tag {
  color: #36bfa8;
  background-color: #f0fffa;
}
</style>
